﻿//Analytics
//baidu
//var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
//document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fa1e159a91b85d498757c88a8006e6de1' type='text/javascript'%3E%3C/script%3E"));

//google
//var _gaq = _gaq || [];
//_gaq.push(['_setAccount', 'UA-24495162-6']);
//_gaq.push(['_setDomainName', '.xxx.com']);
//_gaq.push(['_trackPageview']);
//(function () {
//	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
//	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
//})();

$(document).ready(function () {
    ZWEB.UI.LazyLoad.Run();
});

ZWEB.UI = {
    MakeThumbnail: function (src, width, height) {

        if (src == null)
            return null;
        else
            return src.replace(/(.*)\.(\w{3,4})$/i, "$1_" + width + "_" + height + ".$2");

    },
    EmptyImage: {
        Src: "/web/img/e.gif"
    },
    LazyLoad: {
        _initial: null,
        LastUpdateTime: 0,
        TYPE: {
            "Image": "Image",
            "Flash": "Flash",
            "Function": "Function"
        },
        LOADANIMATION: {
            FADEIN: "fadeIn"
        },
        fnConfig: (function () {
            var funcs = {};
            var _add = function (id, func) {
                funcs[id] = func;
                return this;
            };
            var _get = function (id) {
                if (typeof funcs[id] == "undefined") {
                    return null;
                }
                return funcs[id];
            };
            var _remove = function (id) {
                if (typeof funcs[id] == "undefined") {
                    return false;
                }
                delete funcs[id];
                return true;
            };
            return {
                add: _add,
                get: _get,
                remove: _remove
            };
        })(),
        init: function () {
            var lazyObjects = {
                obj: null,
                length: 0
            };

            var getLazyObjects = function () {
                return $("*[lazyload]");
            };

            var getImageLazyObjects = function () {
                return $("img[lazyload]");
            };

            var getConfigFunction = function (id) {
                return ZWEB.UI.LazyLoad.fnConfig.get(id);
            };

            var initLazyObjects = function (jqObjects, isSetObj) {
                var ret = {};
                if (!jqObjects)
                    return ret;

                var _this, _lazy;
                jqObjects.each(function (i) {
                    _this = $(this);
                    var lazystr = $(this).attr("lazyload");

                    if (lazystr.indexOf(".swf") == -1) {
                        _lazy = splitLazyLoadStr(lazystr);
                        ret[i] = {
                            entity: $(this),
                            type: _lazy.type,
                            lazyload: _lazy.lazyload
                        };

                        _this.attr('src', ZWEB.UI.EmptyImage.Src);
                    }
                    else {
                        ret[i] = {
                            entity: $(this),
                            type: ZWEB.UI.LazyLoad.TYPE.Flash,
                            lazyload: $(this).attr("lazyload")
                        };
                    }
                    lazyObjects.length++;
                });
                if (typeof isSetObj == "boolean" && isSetObj) {
                    setLazyObjects(ret);
                }
                return ret;
            };

            var setLazyObjects = function (objs) {
                lazyObjects.obj = objs;
            };

            var addLazyObjects = function (elem, type, lazyload) {
                if (lazyObjects.obj == null) {
                    lazyObjects.obj = {};
                }
                handler = new Date().getTime() / 1000;
                lazyObjects.obj[handler] = {
                    entity: elem,
                    type: type,
                    lazyload: lazyload
                };
                lazyObjects.length++;
                return;
            };

            var getWindow = function () {
                return {
                    left: document.documentElement.scrollLeft || document.body.scrollLeft,
                    top: document.documentElement.scrollTop || document.body.scrollTop,
                    width: document.documentElement.clientWidth,
                    height: document.documentElement.clientHeight
                }
            };

            var getObject = function (obj) {
                return {
                    left: $(obj).offset().left,
                    top: $(obj).offset().top,
                    width: $(obj).outerWidth(),
                    height: $(obj).outerHeight()
                }
            };

            var splitLazyLoadStr = function (lazyloadstr) {
                var splitIndex = lazyloadstr.indexOf(":");
                var lazyType = ZWEB.UI.LazyLoad.TYPE;
                if (splitIndex <= 0) {
                    return {
                        type: lazyType.Image,
                        lazyload: lazyloadstr
                    };
                }
                var prev = lazyloadstr.slice(0, splitIndex++),
							next = typeof lazyType[prev] != "undefined" ? lazyloadstr.slice(splitIndex) : lazyloadstr;
                prev = next == lazyloadstr ? "Image" : prev;
                return {
                    type: prev,
                    lazyload: next
                };
            };

            var CheckUpdateTime = function () {

                var current_time = new Date().getTime();
                var time_interval = current_time - ZWEB.UI.LazyLoad.LastUpdateTime;

                if (time_interval > 0 && time_interval < 100)
                    return false;
                else {
                    ZWEB.UI.LazyLoad.LastUpdateTime = current_time;
                    return true;
                }
            }

            var each = function () {

                if (!CheckUpdateTime())		//检查一下时间，别太频繁干这个事了
                    return;

                var obj = null;
                var entity = null;
                var lazytype = null;
                var lazyload = null;
                var lazyType = ZWEB.UI.LazyLoad.TYPE;

                var win = getWindow(), dom;
                for (i in lazyObjects.obj) {
                    obj = lazyObjects.obj[i];

                    entity = obj.entity;

                    if (entity == null || entity.length == 0)
                        continue;

                    dom = getObject(entity);

                    if (isIntersect(dom, win) && typeof lazyObjects.obj[i] != "undefined") {
                        lazytype = obj.type;
                        lazyload = obj.lazyload;
                        if (lazytype == lazyType.Image) {
                            loadImage(entity, lazyload);
                            delete lazyObjects.obj[i];
                            lazyObjects.length--;
                            continue;
                        }
                        if (lazytype == lazyType.Function) {
                            loadFunction(entity, lazyload);
                            delete lazyObjects.obj[i];
                            lazyObjects.length--;
                            continue;
                        }
                        if (lazytype == lazyType.Flash) {
                            loadFlash(entity);
                            delete lazyObjects.obj[i];
                            lazyObjects.length--;
                            continue;
                        }
                    }
                }
            };

            var loadImage = function (elem, src) {
                if (typeof loadImage.applying == "undefined") {
                    loadImage.applying = function (elem, imgsrc) {
                        var tagName = elem.attr("tagName") || elem.prop("tagName");
                        if (tagName.toLowerCase() == "img") {
                            elem
									.hide()
									.attr("src", imgsrc)
									.show()
									.removeAttr("lazyload");
                        }
                        else {
                            elem
									.css("background-image", "url(" + imgsrc + ")")
									.fadeIn(800)
									.removeAttr("lazyload");
                        }
                        return;
                    }
                }

                var img = new Image();
                img.src = src;

                if (img.complete) {
                    loadImage.applying(elem, img.src);
                    img = null;
                }
                else {
                    img.onload = function () {
                        loadImage.applying(elem, img.src);
                        img = null;
                    }
                }
            };

            var loadFunction = function (elem, func) {
                if (typeof func != "function") {
                    func = getConfigFunction(func);
                }
                if (!func) {
                    return;
                }
                func.apply(elem);
            };
            var loadFlash = function (elem) {
                var flasharr = [];
                flasharr.push('<embed align="middle" type="application/x-shockwave-flash" allowscriptaccess="always" quality="high" ');
                var width = elem.attr("width");
                var height = elem.attr("height");
                if (typeof width != 'undefined') {
                    flasharr.push(' width="' + width + '" ');
                }
                if (typeof height != 'undefined') {
                    flasharr.push(' height="' + height + '" ');
                }
                var flashsrc = elem.attr("lazyload");
                flasharr.push('src="' + flashsrc + '" ');
                flasharr.push("/>");
                elem.replaceWith(flasharr.join(''));
            }
            var isIntersect = function (rec1, rec2) {
                var lp1 = rec1.width / 2, 		//rec1.left + rec1.width / 2,
							lp2 = rec2.left + rec2.width / 2,
							tp1 = rec1.top + rec1.height / 2,
							tp2 = rec2.top + rec2.height / 2,
							w1 = (rec1.width + rec2.width) / 2,
							h1 = (rec1.height + rec2.height) / 2;
                return Math.abs(lp1 - lp2) <= w1 && Math.abs(tp1 - tp2) <= h1;
            };

            return {
                getLazyObj: getLazyObjects,
                addLazyObj: addLazyObjects,
                initLazyObj: initLazyObjects,
                setLazyObj: setLazyObjects,
                isInter: isIntersect,
                each: each,
                loadImage: loadImage
            }
        },
        Run: function (objs, outer) {
            if (this._initial == null) {
                this._initial = this.init();
            }
            var lz = this._initial;
            if (typeof objs == "undefined" || objs == null || typeof objs.length != "number" || typeof objs.size != "function" || typeof objs.each != "function") {
                lz.initLazyObj(lz.getLazyObj(), true);
            }
            outer = outer || $(window);

            if (outer) {
                outer.scroll(function () {
                    lz.each();
                });
                outer.resize(function () {
                    lz.each();
                });
            }

            lz.each();
            return this;
        },
        Add: function (elem, type, lazyload, func) {
            if (this._initial == null) {
                this._initial = this.init();
            }
            var lz = this._initial;

            lz.addLazyObj(elem, type, lazyload);

            if (type == this.TYPE.Function) {
                this.fnConfig.add(lazyload, func);
            }
            lz.each();
            return this;
        }
    } //End of LazyLoad
};



//弹出窗口管理类
//内部对象的高度是窗口高度减去20，如果有footer，需要再减去20
//对外提供的方法： 
//window_obj.height(h);  //动态设置高度
//window_obj.width(w);   //动态设置宽度
//window_obj.close_window(); //关闭窗口
//window_obj.append(dom_obj); //在窗口中插入一个对象
//window_obj.setTitle(title_text);  //设置标题栏文字
//window_obj.setContent(new_content); //重设内容

function zPopWindow(opt) {
    var _this = this;

    //以下是zPopWindow创建时的各种选项参数以及缺省值
    var defaultOptions = {


        /* 此处新增了设置，为实现自定义的弹出窗口 */
        showTitle: true,                                //是否含有标题栏
        wndClassName: "zwindow_panel",   //窗口样式
        dragContainerID: null,                       //拖拽区域ID
        /* 结束 */


        title: "zWindow", 		    //标题文字
        alertWindow: false, 		//显示不同的警告条，为alert窗口单独做的
        content: null, 				//窗口的内容，必须是一个
        footerContent: null, 		//页脚的内容
        x: -1, 						//窗口的起始位置，x坐标
        y: -1, 						//窗口的起始位置，y坐标
        width: "auto", 				//窗口宽度
        height: "auto", 			//窗口高度
        showFooter: false, 			//是否显示页脚 
        draggable: true, 			//窗口是否可以拖拽
        onOpen: null, 				//窗口创建完毕时的回调方法
        onClose: null, 				//关闭窗口时的回调方法
        uniqueWindowName: "", 	//窗口名称，一个唯一的字符串。一旦发现有相同名字的窗口，关闭之后再生成新的，确保窗口唯一。
        exclusive: false, 		//如果设置为true，则窗口为独占模式
        animateClose: false, 	//如果设置为true，则关闭窗口时会逐渐消失，而不是立刻关闭
        closeSpeed: 3000,
        focusAfterClose: null
    };


    opt = $.extend({}, defaultOptions, opt);

    var window_height = $(window).height();
    var window_width = $(window).width();

    if (isNaN(opt.width) && opt.width > window_width)
        opt.width = window_width;

    if (isNaN(opt.width) && opt.height > window_height)
        opt.height = window_height;


    /* 初始化窗口组件 */
    /* 为窗口自定义样式做出的修改，替换了下面的代码：
    *   var zwindow_obj = $('<div>').addClass('zwindow_panel').css({ "position": "absolute", "background-color": "#FFF" }).width(opt.width).height(opt.height).css('opacity', 1);
    */
    var zwindow_obj = $('<div>').addClass(opt.wndClassName).css({ "position": "absolute" }).width(opt.width).height(opt.height);
    /*结束*/


    //<a id="thickcloser" class="thickclose" href="#">×</a>
    var close_icon = $("<div>").addClass("zwindow_close_box").attr('title', '关闭');

    var title_bar_text = $("<div>").addClass("zwindow_title_text").width(opt.width - 50).text(opt.title);
    var title_bar = $('<div>').addClass('zwindow_header').addClass("zwindow_header_normal")
							  .append(title_bar_text);


    title_bar.append(close_icon);

    if (opt.alertBar)
        title_bar.addClass("z_window_alert");

    var footer_bar = $('<div>').addClass("zwindow_footer").addClass("ui-widget-content").css('style', 'block');
    var foot_end_e = $('<div>').addClass("ui-resizable-handle ").addClass("ui-resizable-e");
    var foot_end_s = $('<div>').addClass("ui-resizable-handle ").addClass("ui-resizable-s");
    var foot_end_se = $('<div>').addClass("ui-resizable-handle ").addClass("ui-resizable-se").addClass("ui-icon").addClass("ui-icon-gripsmall-diagonal-se");

    this.close_window = close_window;

    close_icon.click(function () {
        close_window();
        return false;
    });


    /* 为无标题做出的修改，替换了下面的代码：
    *   zwindow_obj.zMakeTop().append(title_bar);
    */
    zwindow_obj.zMakeTop();
    if (opt.showTitle) {
        zwindow_obj.append(title_bar);
    }
    /*结束*/

    var ajax_cover = null;
    if (opt.exclusive) {
        ajax_cover = $("<div>").addClass('ajaxCover').bgiframe().css('z-index', zwindow_obj.css('z-index') - 1).appendTo(document.body);
        push_focused_obj();
    }


    //主元素
    if (opt.content != null) {
        zwindow_obj.append($(opt.content));
    }

    //处理一下脚底
    if (opt.showFooter) {

        if (opt.footerContent != null)
            footer_bar.append($(opt.footerContent));

        zwindow_obj.append(footer_bar).append(foot_end_e)
					.append(foot_end_s).append(foot_end_se);
    }

    if (opt.uniqueWindowName != '') //设置了唯一名，那就得登记一下，便于删除
    {
        if ($(document).data("zWindow:" + opt.uniqueWindowName) != null)
            $(document).data("zWindow:" + opt.uniqueWindowName).close_window();
        $(document).data("zWindow:" + opt.uniqueWindowName, _this);
    }


    zwindow_obj.hide().appendTo(document.body); //现在才加入

    if (opt.x == -1) {

        opt.x = (window_width - zwindow_obj.width()) / 2 + $(window).scrollLeft(); // Math.round((window_width - zwindow_obj.width()) / 2);
        if ((opt.x + zwindow_obj.width()) > window_width)
            opt.x = window_width - zwindow_obj.width() - 20;
    }

    if (opt.y == -1) {
        opt.y = (window_height - zwindow_obj.height()) / 2 + $(window).scrollTop();   //Math.round((window_height - zwindow_obj.height()) / 2);
        if (opt.y < 0)
            opt.y = 0;
    }

    //设置拖拽
    if (opt.draggable) {
        /* 为自定义拖拽区域做出的修改，替换了下面的代码：
        *  zwindow_obj.easydrag().setHandler(title_bar);
        */
        if (opt.dragContainerID)
            zwindow_obj.easydrag().setHandler($("#" + opt.dragContainerID));
        else
            zwindow_obj.easydrag().setHandler(title_bar);
    }

    zwindow_obj.css('left', opt.x + 'px').css('top', opt.y + 'px').show(); //结束，返回



    /* 为窗口创建完成时执行回调，添加了下面的代码：*/
    if (opt.onOpen) {
        opt.onOpen();
    }
    /*结束*/


    function close_window() {

        if (opt.animateClose && opt.closeSpeed > 0)
            zwindow_obj.hide(opt.closeSpeed, "linear", _close_window)
        else
            _close_window();

        function _close_window() {

            if (opt.exclusive && ajax_cover != null) //如果是独占的，得清理一下
            {
                ajax_cover.remove();
                pop_focused_obj();
            }

            zwindow_obj.remove(); //这个顺序还是挺重要的，如果zwindow_obj提前remove，那么pop_focus就没效果了

            if (opt.uniqueWindowName != '') { //退出的时候，这个也需要清理一下
                $(document).removeData("zWindow:" + opt.uniqueWindowName);
            }

            if (opt.onClose)
                opt.onClose();
        }
    }

    //设置高度
    this.height = function (h) {
        zwindow_obj.height(h);
    }

    //设置宽度
    this.width = function (w) {
        zwindow_obj.width(w);
    }

    //在主显示区附加一个对象
    this.append = function (o) {
        zwindow_obj.append(o);
    }

    //设置标题
    this.setTitle = function (t) {
        title_bar_text.text(t);
    }

    //重设内容
    this.setContent = function (new_content) {
        zwindow_obj.children(":eq(1)").replaceWith(new_content);
    }

    //将当前的聚焦对象保存
    function push_focused_obj() {
        var active_elem = $(document.body).find(":focus");
        zwindow_obj.data("focused_doc", active_elem).focus();
        //active_elem.blur();
    }

    //将当前的聚焦对象恢复
    function pop_focused_obj() {

        var backed_elem = zwindow_obj.data("focused_doc");

        if (opt.focusAfterClose != null)
            $(opt.focusAfterClose).focus();
        else if (backed_elem != null) {
            backed_elem.focus();
        }

        zwindow_obj.removeData("focused_doc");
    }
}

function zReloadValidationImage(click_obj, img_obj) {

    if (img_obj == null) { //只传了一个对象进去

        if ($(click_obj).is('img')) //是图片本身
            img_obj = $(click_obj);
        else if ($(click_obj).is('a'))
            img_obj = $(click_obj).prev();
    }
    else
        img_obj = $(img_obj);

    var img_orig_src = img_obj.data('orig_src');
    if (img_orig_src == null) {
        img_orig_src = img_obj.attr('src');
        img_obj.data('orig_src', img_orig_src);
    }

    img_obj.attr('src', img_orig_src + "?rand=" + Math.random());
}


/* 格式化数字显示
* zFormatNumber(12345.999,'#,##0.00'); 
* zFormatNumber(12345.999,'#,##0.##'); 
* zFormatNumber(123,'000000'); 
*/
function zFormatNumber(num, pattern) {
    var strarr = num ? num.toString().split('.') : ['0'];
    var fmtarr = pattern ? pattern.split('.') : [''];
    var retstr = '';

    // 整数部分  
    var str = strarr[0];
    var fmt = fmtarr[0];
    var i = str.length - 1;
    var comma = false;
    for (var f = fmt.length - 1; f >= 0; f--) {
        switch (fmt.substr(f, 1)) {
            case '#':
                if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                break;
            case '0':
                if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                else retstr = '0' + retstr;
                break;
            case ',':
                comma = true;
                retstr = ',' + retstr;
                break;
        }
    }
    if (i >= 0) {
        if (comma) {
            var l = str.length;
            for (; i >= 0; i--) {
                retstr = str.substr(i, 1) + retstr;
                if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
            }
        }
        else retstr = str.substr(0, i + 1) + retstr;
    }

    retstr = retstr + '.';
    // 处理小数部分  
    str = strarr.length > 1 ? strarr[1] : '';
    fmt = fmtarr.length > 1 ? fmtarr[1] : '';
    i = 0;
    for (var f = 0; f < fmt.length; f++) {
        switch (fmt.substr(f, 1)) {
            case '#':
                if (i < str.length) retstr += str.substr(i++, 1);
                break;
            case '0':
                if (i < str.length) retstr += str.substr(i++, 1);
                else retstr += '0';
                break;
        }
    }
    return retstr.replace(/^,+/, '').replace(/\.$/, '');
}


// 日期时间格式化方法
// 使用例子  var now = new Date();
//		    var x = zFormatDate(now, "yyyy-MMMM-dd HH:mm:ss tt");
//          alert(x) -> 结果是
// 支持的格式：
// yy 不包含纪元的年份。如果不包含纪元的年份小于 10，则显示具有前导零的年份。
// yyyy 包括纪元的四位数的年份。
// MMMM 月份的中文名称。
// MM 月份数字。一位数的月份有一个前导零。
// dddd 周中某天的完整名称，如周一
// dd 月中的某一天。一位数的日期有一个前导零。
// hh 12 小时制的小时。一位数的小时数有前导零。
// HH 24 小时制的小时。一位数的小时数有前导零。
// mm 分钟。一位数的分钟数有一个前导零。
// ss 秒。一位数的秒数有一个前导零。
// tt 显示am(上午），pm（下午）

function zFormatDate(in_obj, f) {

    if (!in_obj || !f)
        return "";

    var d = in_obj;
    if (d.substring)
        d = new Date(in_obj);

    // a global month names array
    var gsMonthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];

    // a global day names array
    var gsDayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

    return f.replace(/(yyyy|yy|MMMM|MM|dddd|ddd|dd|d|HH|hh|mm|ss|tt)/g,
        function (val) {
            switch (val) {
                case 'yy': return d.getFullYear().toString().substr(2);
                case 'yyyy': return d.getFullYear();
                case 'MMMM': return gsMonthNames[d.getMonth()];
                case 'MM': return zFormatNumber((d.getMonth() + 1), '00');
                case 'dddd': return gsDayNames[d.getDay()];
                case 'ddd': return gsDayNames[d.getDay()].substr(0, 3);
                case 'dd': return zFormatNumber(d.getDate(), '00');
                case 'd': d.getDate();
                case 'HH': return zFormatNumber(d.getHours(), '00');
                case 'hh': return zFormatNumber(((h = d.getHours() % 12) ? h : 12), '00');
                case 'mm': return zFormatNumber(d.getMinutes(), '00');
                case 'ss': return zFormatNumber(d.getSeconds(), '00');
                case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
            }
        }
    );
}

//EasyDrag，拖拽窗口用的，放主库吧，都需要
(function ($) {

    // to track if the mouse button is pressed
    var isMouseDown = false;

    // to track the current element being dragged
    var currentElement = null;

    // global position records
    var lastMouseX;
    var lastMouseY;
    var lastElemTop;
    var lastElemLeft;

    var min_x;
    var min_y;
    var max_x;
    var max_y;

    // if user is holding any handle or not
    var holdingHandler = false;
    $.updateWindowBorder = function (e) {
        min_x = $(window).scrollLeft();
        max_x = min_x + $(window).width() - currentElement.width() - 2;
        min_y = $(window).scrollTop();
        max_y = min_y + $(window).height() - currentElement.height() - 2;
    }

    // returns the mouse (cursor) current position
    $.getMousePosition = function (e) {
        var posx = 0;
        var posy = 0;

        if (!e) e = window.event;

        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }

        return { 'x': posx, 'y': posy };
    };

    // updates the position of the current element being dragged
    $.updatePosition = function (e) {

        var pos = $.getMousePosition(e);

        var spanX = (pos.x - lastMouseX);
        var spanY = (pos.y - lastMouseY);

        var new_x = lastElemLeft + spanX;
        var new_y = lastElemTop + spanY;

        if (new_x < min_x)
            new_x = min_x;
        else if (new_x > max_x)
            new_x = max_x;

        if (new_y < min_y)
            new_y = min_y;
        else if (new_y > max_y)
            new_y = max_y;

        currentElement.css("top", new_y).css("left", new_x);
    };

    // when the mouse is moved while the mouse button is pressed
    $(document).mousemove(function (e) {
        if (isMouseDown) {
            $.updatePosition(e);
            return false;
        }
    });

    // when the mouse button is released
    $(document).mouseup(function (e) {
        if (isMouseDown) {
            isMouseDown = false;
            return false;
        }
    });

    // set a child element as a handler
    $.fn.setHandler = function (handlerTarget) {
        return this.each(function () {
            var draggable = this;

            // reset cursor style
            $(draggable).css("cursor", "");

            if (handlerTarget == null)
                handlerTarget = $(this);

            // bind event handler
            handlerTarget.mousedown(function (e) {
                holdingHandler = true;
                $(draggable).trigger('mousedown', e);
            });

            // bind event handler
            handlerTarget.mouseup(function (e) {
                holdingHandler = false;
            });
        });
    }

    // set an element as draggable - allowBubbling enables/disables event bubbling
    $.fn.easydrag = function () {

        return this.each(function (opt) {

            // change the mouse pointer
            $(this).css("cursor", "move").css("position", "absolute");

            // when an element receives a mouse press
            $(this).mousedown(function (e) {

                // just when "on" or "handler"
                if (!holdingHandler)
                    return true;

                // set z-index
                $(this).zMakeTop();

                // update track variables
                isMouseDown = true;
                currentElement = $(this);

                $.updateWindowBorder(e);

                // retrieve positioning properties
                var pos = $.getMousePosition(e);
                lastMouseX = pos.x;
                lastMouseY = pos.y;

                lastElemTop = this.offsetTop;
                lastElemLeft = this.offsetLeft;

                $.updatePosition(e);

                return false;
            });
        });
    };

})(jQuery);

//类似系统的alert，但不阻塞，立刻返回false
function zAlert(msg, opt) {

    opt = $.extend({
        autoHide: false, 		//是否自动消失
        hidingSpeed: 3000, 		//自动消失的时间
        onClose: null, 		    //点击确认和关闭之后运行的方法  
        onOK: null, 		    //只点击确认之后运行的方法
        changeFocus: true,      //修改focus，配合blur用的
        focusAfterClose: null,  //关闭窗口后恢复的焦点在哪个对象，缺省为空
        customFunction: null,   //自定义方法
        onOpen: null
    }, opt);


    var confirm_button = $("<div class='zwindow_btn'>").append("<input class='confirm' type='button' value='确定'/>");

    var alert_text = $("<div class='zwindow_content'>").append($("<div class='zwindow_msg'>").html(msg));

    if (!opt.autoHide)
        alert_text.append(confirm_button);

    var new_module_window = new zPopWindow({
        title: "提示信息",
        width: 400,
        content: alert_text,
        exclusive: true,
        alertBar: true,
        animateClose: opt.autoHide,
        closeSpeed: opt.hidingSpeed,
        onClose: opt.onClose,
        focusAfterClose: opt.focusAfterClose,
        onOpen: opt.onOpen
    });

    //自定义方法
    //_check
    if (opt.customFunction != null) {
        new opt.customFunction();
    }

    if (!opt.autoHide) {
        confirm_button.children("input").bind('click', function () {

            if (opt.onOK != null)
                opt.onOK();

            new_module_window.close_window();

            if (window.timer)
                clearTimeout(timer); //清除自定义函数里面的定时器，暂时用的，为了解决一个BUG
        });

        setTimeout(function () {
            confirm_button.children("input").focus();
        }, 100);

    }
    else {
        new_module_window.close_window();

        if (window.timer)
            clearTimeout(timer); //清除自定义函数里面的定时器，暂时用的，为了解决一个BUG
    }

    return false; //zAlert永远返回false，为了让上一级知道，出错啦				
}

//初始化一个菜单或者联动菜单，
function zInitSelect(select_objs, opt) {

    if (select_objs == null || !select_objs.jquery || select_objs.length == 0) //必须非空，并且必须是jquery的对象
        return;

    opt = $.extend({}, {
        WSFunc: null, 		//这个必须有，不能为空
        initValues: null, 	//缺省没有ID，如果有，必须是
        WSProgram: null, //缺省用本页回调
        extra_param: null,
        callback: null
    }, opt);

    if (opt.initValues != null && !$.isArray(opt.initValues))
        opt.initValues = [opt.initValues];

    //前n个绑上事件
    select_objs.each(function (i) {
        if (i > select_objs.length - 2) //如果是1个，就啥也不做了，载入就是了，如果是2个，就只绑第一个，3个，就只绑前两个，以此类推
            return;

        $(this).data('next_select_obj', select_objs.eq(i + 1)).data('next_select_index', (i + 1))   //把下一菜单的一些数据绑上
			   .change(function () {
			       var this_selected_value = $(this).val();

			       var next_select = $(this).data('next_select_obj');
			       var next_index = $(this).data('next_select_index');

			       if (this_selected_value == "_no_select") {			//啥也没选，这个也要联动
			           next_select[0].options.length = next_select[0].options.length == 0 ? 0 : 1; //除了标题，都清空
			           next_select.change();
			       }
			       else
			           load_ws_selection(next_index, next_select, this_selected_value);
			   });
    });


    //初始化，先载入第1个select的内容
    load_ws_selection(0, select_objs.eq(0), null, opt.initValues);

    //载入一个Select，并设置初始值
    function load_ws_selection(obj_index, obj_selection, parent_value, init_values) {

        var call_obj = new Object();
        call_obj.obj_index = obj_index;
        call_obj.parent_value = parent_value;
        call_obj.extra_param = opt.extra_param;

        ZWEB.AJAX.Call(opt.WSFunc, load_selection_callback, call_obj,
        { 
            ws_path: opt.WSProgram,
            ajax_lock: false
        });

        //查询结果的操作
        function load_selection_callback(r_code, r_msg, r_obj) {
            if (r_code != ZWEB.AJAX.WS_ReturnCode.SUCCESS)
                return zAlert(r_msg);

            load_selection_data(r_obj);
        }

        function load_selection_data(select_data) {

            if (obj_selection[0].options.length > 0)
                obj_selection[0].options.length = 0; //清空

            if (select_data == null)
                return zAlert("菜单数据载入出错，请联系技术:" + opt.WSFunc);

            var init_value = null;
            if (init_values != null && obj_index < init_values.length)
                init_value = init_values[obj_index];

            var select_options = obj_selection[0].options;

            for (var i = 0; i < select_data.length; i++) {

                var option_value = select_data[i]["value"];
                var option_text = select_data[i]["text"];

                var new_option = new Option();

                new_option.text = option_text;
                new_option.value = option_value;


                if (init_value == null)
                    select_options.add(new_option);
                else if (option_value == init_value) {
                    new_option.selected = true;
                    select_options.add(new_option);
                }
                else
                    select_options.add(new_option);
            }

            if (init_values == null) //系统自动的
            {
                if (obj_index > 0)
                    obj_selection.change();
            }
            else if (obj_index < init_values.length - 1)
                load_ws_selection(obj_index + 1, select_objs.eq(obj_index + 1), init_values[obj_index], init_values);
            else {

                obj_selection.change();
            }
        }
    }
}

//类似系统的confirm,但是得使用callback，不可能真正阻塞的
//如果确认，就调用callback，如果取消，就啥也不干

//_check
//如果确认，就调用confirm_callback，如果取消，就调用cancel_callback
function zConfirm(message, opt, event) {

    opt = $.extend({
        onConfirm: null, 		    //点击确认按钮的回调方法  
        onCancel: null, 		    //点击取消按钮的回调方法
        ConfirmCharacter: "确定",     //确定按钮上的字
        CancelCharacter: "取消"       //取消按钮上的字
    }, opt);

    //_check
    var confirm_button = $("<input class='confirm' type='button' value='" + opt.ConfirmCharacter + "'/>");
    var cancel_button = $("<input class='cancel' type='button' value='" + opt.CancelCharacter + "'/>");

    var alert_text = $("<div class='zwindow_content'>").append($("<div class='zwindow_msg'>").html(message))
                                                       .append($("<div class='zwindow_btn'>").append(confirm_button).append(cancel_button));

    //    var confirm_button = $("<input type='button' value='确认'/>").css('font-size', '14px').css('margin-bottom', '15px');
    //    var cancel_button = $("<input type='button' value='取消'/>").css('font-size', '14px').css('margin-bottom', '15px').css('margin-left', '15px');

    //    var msg_p = $("<p>").text(message).css('font-size', '18px').css('margin', '10px').css('margin-bottom', '15px')

    //    var alert_text = $("<div>").width(300).css('margin', '0 auto 0 auto').css('text-align', 'center')
    //					 .append(msg_p).append(confirm_button).append(cancel_button);

    var confirm_window = null;

    if (event != null) { //定位在鼠标点
        var pos = $.getMousePosition(event);

        var confirm_window = new zPopWindow({
            title: "请确认",
            width: 400,
            content: alert_text,
            exclusive: true,
            alertBar: true,
            x: pos.x,
            y: pos.y
        });
    }
    else { //定位在屏幕中央
        var confirm_window = new zPopWindow({
            title: "请确认",
            width: 400,
            content: alert_text,
            exclusive: true,
            alertBar: true
        })
    }


    confirm_button.click(function () {  //_check
        //do_callback(true);

        confirm_window.close_window(); //都是要关的

        if (opt.onConfirm != null)//如果没有回调方法，就啥也不干
            opt.onConfirm();
    });

    cancel_button.click(function () {
        //do_callback(false);

        confirm_window.close_window(); //都是要关的

        if (opt.onCancel != null)//如果没有回调方法，就啥也不干
            opt.onCancel();
    });


    //    function do_callback(confirmed) {

    //        confirm_window.close_window(); //都是要关的

    //        if (confirmed && callback != null)
    //            callback();

    //    }

    return false; //怕有人认为这个的表现和系统的confirm一样，所以缺省返回false
}

//jQuery扩展
(function ($) {
    //设置一个Select为一个已选值
    $.fn.setSelectedValue = function (SelectedValue) {
        return this.each(function () {
            var objSelect = this;
            if (objSelect.options == null || objSelect.options.length == 0)
                return;
            objSelect.options[0].selected = true;
            for (var i = 0; i < objSelect.options.length; i++) {
                if (objSelect.options[i].value == SelectedValue) {
                    objSelect.options[i].selected = true;
                    break;
                }
            }
        });
    };
    //设置一个Select为一个已选文本
    $.fn.setSelectedText = function (SelectedText) {
        return this.each(function () {
            var objSelect = this;
            objSelect.options[0].selected = true;
            for (var i = 0; i < objSelect.options.length; i++) {
                if (objSelect.options[i].text == SelectedText) {
                    objSelect.options[i].selected = true;
                    break;
                }
            }
        });
    };
    //对齐对象
    $.fn.Align = function (AlignOpt) {
        return this.each(function () {
            alignedObj = $(this);
            if (typeof AlignOpt == 'undefined' || AlignOpt == null) AlignOpt = "both";
            if (AlignOpt == "none") return alignedObj;
            var containerHeight = alignedObj.parent().height();
            var containerWidth = alignedObj.parent().width();
            if (!alignedObj.height() || !alignedObj.width())
                return alignedObj;
            if (AlignOpt == "both" || AlignOpt == "vertical")
                if (alignedObj.height() < containerHeight - 1)
                    alignedObj.css('top', Math.floor((containerHeight - alignedObj.height()) / 2) + 'px');
                else
                    alignedObj.css('top', '0px');
            if (AlignOpt == "both" || AlignOpt == "horizontal")
                if (alignedObj.width() < containerWidth - 1)
                    alignedObj.css('left', Math.floor((containerWidth - alignedObj.width()) / 2) + 'px');
                else
                    alignedObj.css('left', '0px');
            return alignedObj;
        });
    };
})(jQuery);

//日期格式化方法，支持标准日期，以及yyyy-mm-dd HH:MM:ss的格式
var zparse_date_time_regex = /^(\d{2,4})[\-](\d{1,2})[\-](\d{1,2})\s+(\d{1,2})[\:](\d{1,2})[\:](\d{1,2})$/;
function zParseDate(in_str) {
    if (in_str == 'undefined' || in_str == null)
        return null;

    var try_date_parse = new Date(in_str);
    if (!isNaN(try_date_parse.valueOf()))
        return try_date_parse;

    var match_date_time = zparse_date_time_regex.exec(in_str);
    if (match_date_time != null) {
        var m_m = parseInt(match_date_time[2]) - 1;
        return new Date(match_date_time[1], m_m, match_date_time[3], match_date_time[4], match_date_time[5], match_date_time[6], 0);
    }
    else if (in_str.length < 12) //避免死循环
        return zParseDate(in_str + " 00:00:00");

}